package com.xja.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.cloud.ai.dashscope.chat.MessageFormat;
import com.alibaba.cloud.ai.dashscope.common.DashScopeApiConstants;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xja.mapper.TongueMapper;
import com.xja.model.entity.Tongue;
import com.xja.model.vo.req.TongueDiagnosisReqVO;
import com.xja.service.ITongueService;
import com.xja.utils.ChatClientHolder;
import com.xja.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.content.Media;
import org.springframework.stereotype.Service;
import org.springframework.util.MimeTypeUtils;

import java.net.URL;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 舌诊表 服务实现类
 * </p>
 *
 * @author caijg
 * @since 2025-06-08
 */
@Service
@RequiredArgsConstructor
public class TongueServiceImpl extends ServiceImpl<TongueMapper, Tongue> implements ITongueService {

    private final ChatClientHolder chatClientHolder;

    @Override
    public Tongue diagnosis(TongueDiagnosisReqVO tongueDiagnosisReqVO) {
        // 1.获取舌苔图片
        String imageUrl = tongueDiagnosisReqVO.getUrl();

        // 2.获取视觉大模型生成的舌苔特征描述
        Tongue tongue = getVisuallyModelResult(imageUrl);

        // 3.将诊断结果保存到数据库
        tongue.setUserId(tongueDiagnosisReqVO.getUserId());
        tongue.setImageUrl(imageUrl);
        tongue.setCreateTime(LocalDateTime.now());
        tongue.setId(null);
        this.save(tongue);

        // 4.返回舌苔描述
        return tongue;
    }

    /**
     * 调用视觉大模型，获取舌苔特征
     *
     * @param imageUrl 舌苔图片的URL
     * @return 舌苔的特征
     */
    private Tongue getVisuallyModelResult(String imageUrl) {
        try {
            // 1.获取舌苔大模型客户端
            ChatClient tongueChatClient = chatClientHolder.getTongueChatClient();
            // 2.添加图片内容

            List<Media> mediaList = List.of(new Media(MimeTypeUtils.IMAGE_PNG, new URL(imageUrl).toURI()));
            UserMessage message = UserMessage
                    .builder()
                    .text("舌苔图片如下：")
                    .media(mediaList)
                    .metadata(new HashMap<>())
                    .build();
            message.getMetadata().put(DashScopeApiConstants.MESSAGE_FORMAT, MessageFormat.IMAGE);
//            UserMessage message = new UserMessage("舌苔图片如下：");

            // 3.返回响应
            return tongueChatClient.prompt()
                    .messages(message)
                    .call()
                    .entity(Tongue.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取历史诊断记录
     */
    @Override
    public JSON history() {
        // 1.获取当前用户id
        Long userId = UserContext.getUid();

        // 2.根据用户id查询历史诊断记录
        List<Tongue> list = this.query()
                .eq("user_id", userId)
                .orderByDesc("create_time")
                .list();

        // 3.返回历史诊断记录
        return JSONUtil.parse(list);
    }

    /**
     * 删除指定id的舌诊记录
     *
     * @param ids 舌诊记录id列表
     */
    @Override
    public Boolean delete(ArrayList<String> ids) {
        // 1.删除指定id的记录
        return this.removeByIds(ids);
    }
}
